//
//  QRViewController.m
//  QRCode
//
//  Created by tgs on 2017/7/6.
//  Copyright © 2017年 tgs. All rights reserved.
//

#import "QRViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioToolbox.h>

@interface QRViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    AVCaptureSession *session;
    AVCaptureVideoPreviewLayer *layer;
    UIView *lineView;
    UIView *scanView;
}

@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, strong) UIButton *btnLamp;//控制照明灯按钮

@end

@implementation QRViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    [self stepUI];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self systemLightSwitch:NO];
}

- (void)stepUI{
    
//    UINavigationItem *rightItem = [[UINavigationItem alloc] initWithTitle:@"相册"];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"相册" style:UIBarButtonItemStylePlain target:self action:@selector(choicePhoto)];

    
    //获取设备
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    //初始化对象
    session = [[AVCaptureSession alloc] init];
    
    //创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    NSError *error = nil;
    
    if (input) {
        [session addInput:input];
    }
    else {
        NSLog(@"error %@",[error localizedDescription]);
    }
    
    //创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    
    //设置代理，在主线程刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    //高质量采集串
    [session setSessionPreset:AVCaptureSessionPresetHigh];
    [session addOutput:output];
    
    //设置扫描二维码的编码格式
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode];
    
    scanView = [[UIView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/2 - 100, self.view.bounds.size.height/2 - 100, 200, 200)];
    scanView.layer.borderColor = [UIColor greenColor].CGColor;
    scanView.layer.borderWidth = 1;
    
    //获取屏幕的frame
    CGRect viewRect = self.view.frame;
    //获取扫描容器的frame
    CGRect containerRect = scanView.frame;
    CGFloat x = containerRect.origin.y / viewRect.size.height;
    CGFloat y = containerRect.origin.x / viewRect.size.width;
    CGFloat width = containerRect.size.height / viewRect.size.height;
    CGFloat height = containerRect.size.width / viewRect.size.width;
    //rectOfInterest属性设置设备的扫描范围
    output.rectOfInterest = CGRectMake(x, y, width, height);
    
    
    layer = [AVCaptureVideoPreviewLayer layerWithSession:session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    layer.frame = self.view.bounds;
    layer.backgroundColor = [UIColor clearColor].CGColor;
    layer.borderWidth = 1;
    layer.borderColor = [UIColor grayColor].CGColor;
    
    [self.view.layer addSublayer:layer];
    [self.view addSubview:scanView];
    
    
    UIView *viewMask = [[UIView alloc] initWithFrame:self.view.bounds];
    viewMask.backgroundColor = [UIColor blackColor];
    viewMask.alpha = 0.4;
    [self.view addSubview:viewMask];
    
    //扣出一块空白区域
    //create path
    UIBezierPath *path = [UIBezierPath bezierPathWithRect:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height)];
    
    [path appendPath:[[UIBezierPath bezierPathWithRoundedRect:CGRectMake(self.view.bounds.size.width/2 - 100, self.view.bounds.size.height/2 - 100, 200, 200) cornerRadius:0] bezierPathByReversingPath]];
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    shapeLayer.path = path.CGPath;
    [viewMask.layer setMask:shapeLayer];
    
    
    [self animate];
    [session startRunning];
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [self animate];
    }];
    
    //打开照明灯按钮
    _btnLamp = [UIButton buttonWithType:UIButtonTypeCustom];
    [_btnLamp setTitle:@"打开照明" forState:0];
    [_btnLamp setTitleColor:[UIColor whiteColor] forState:0];
    _btnLamp.frame = CGRectMake(self.view.bounds.size.width/2 - 50, scanView.frame.origin.y + scanView.frame.size.height + 20, 100, 44);
    [self.view addSubview:_btnLamp];
    [_btnLamp addTarget:self action:@selector(openLamp:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)choicePhoto{
    //调用相册
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    imagePicker.delegate = self;
    [self presentViewController:imagePicker animated:YES completion:nil];
}
//选中图片的回调
-(void)imagePickerController:(UIImagePickerController*)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    NSString *content = nil;
    //取出选中的图片
    UIImage *pickImage = info[UIImagePickerControllerOriginalImage];
    UIImage *newImage = [self scaleImage:pickImage]; //图片过大会无法扫描二维码
    NSData *imageData = UIImagePNGRepresentation(newImage);
    CIImage *ciImage = [CIImage imageWithData:imageData];
    
    //创建探测器
    //CIDetectorTypeQRCode表示二维码，这里选择CIDetectorAccuracyLow识别速度快
    CIDetector *detector = [CIDetector detectorOfType:CIDetectorAccuracyLow context:nil options:@{CIDetectorAccuracy: CIDetectorAccuracyLow}];
    NSArray *feature = [detector featuresInImage:ciImage];
    
    //取出探测到的数据
    for (CIQRCodeFeature *result in feature) {
        content = result.messageString;// 这个就是我们想要的值
    }
    if (self.block) {
        self.block(content);
    }
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)animate{

    UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 200, 1)];
    line.backgroundColor = [UIColor greenColor];
    [scanView addSubview:line];
    [UIView animateWithDuration:3 animations:^{
        line.frame = CGRectMake(0,200, 200,1);
    } completion:^(BOOL finished) {
        [line removeFromSuperview];
    }];
    
}

//打开照明灯光比照明灯
- (void)openLamp:(UIButton *)sender{
    UIButton *btn = sender;
    btn.selected = !btn.selected;
    if (btn.selected) {//打开
        [self systemLightSwitch:YES];
    }
    else {//关闭
         [self systemLightSwitch:NO];
    }
}
- (void)systemLightSwitch:(BOOL)open
{
    if (open) {
        [_btnLamp setTitle:@"关闭照明" forState:UIControlStateNormal];
    } else {
        [_btnLamp setTitle:@"打开照明" forState:UIControlStateNormal];
    }
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if ([device hasTorch]) {
        [device lockForConfiguration:nil];
        if (open) {
            [device setTorchMode:AVCaptureTorchModeOn];
        } else {
            [device setTorchMode:AVCaptureTorchModeOff];
        }
        [device unlockForConfiguration];
    }
}


#pragma mark-AVCaptureMetadataOuputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    AudioServicesPlaySystemSound(1000);
    NSString *qrStr = nil;
    for (AVMetadataObject *metadata in metadataObjects) {
        if ([metadata.type isEqualToString:AVMetadataObjectTypeQRCode]) {
            qrStr = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
            break;
        }
    }
    NSLog(@"QRStr--: %@",qrStr);
    [session stopRunning];
    [_timer invalidate];
    _timer = nil;
    if (self.block) {
        self.block(qrStr);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (UIImage *)scaleImage:(UIImage *)image{
    
    UIImage *bigImage = image;
    float bigHeight = bigImage.size.height;
    float bigWidth = bigImage.size.width;
    float newWidth = 0;
    float newHeight = 0;
    if(bigWidth > bigHeight) {
        newHeight =256.0f;
        newWidth = bigWidth / bigHeight * newHeight;
    }
    else
    {
        newWidth =256.0f;
        newHeight = bigHeight / bigWidth * newWidth;
    }
    CGRect rect = CGRectMake(0.0,0.0, newWidth, newHeight);
    UIGraphicsBeginImageContext(rect.size);
    [bigImage drawInRect:rect];
    image =UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
